package api;


import com.alibaba.fastjson.JSONObject;
import donain.Product;
import exception.ProductException;
import service.ProductService;
import utilts.GetRequestJsonUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import utilts.Response;
import utilts.ResponseCode;

public class addProductServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        req.getRequestURL();
        JSONObject jsonObject= null;
        Response build=null;
        try {

            jsonObject = GetRequestJsonUtils.getRequestJsonObject(req);
        } catch (Exception e) {
            e.printStackTrace();
            build=Response.build(ResponseCode.ERROR,e.getMessage());
        }
        ProductService productService=new ProductService();
        String products=jsonObject.getString("products");
        Product  product=JSON.parseObject(products, Product.class);
        product.setId(UUID.randomUUID().toString());
//        第二步：转换成java对象
        boolean isadd=false;
        try {
            if(productService.addProduct(product)){
    //            build=Response.build(ResponseCode.SUCCESS,"你已注册成功，快去登陆邮箱激活账号！");
                build=Response.build(ResponseCode.SUCCESS_ADD_PRODUCT);
                isadd=true;
            }
            else {
                build=Response.build(ResponseCode.ERROR_REGISTERT);
                isadd=false;
            }
        } catch (ProductException e) {
            e.printStackTrace();
        }

//        第四步：反馈浏览器修改信息json数据
        if(isadd){
            build = Response.build(ResponseCode.SUCCESS_ADD_PRODUCT);
            resp.getWriter().write(JSON.toJSON(build).toString());
        }else {
            build = Response.build(ResponseCode.EEROR_ADD_PRODUCT);
            resp.getWriter().write(JSON.toJSON(build).toString());
        }

    }
}
